package com.xiwen.plugin.aspect;

import com.xiwen.plugin.redis.RedisUtil;
import com.xiwen.common.SpringContextHolder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

@Controller
@RequestMapping("/ManyThread")
public class MyReenrantLock implements Runnable {

    private Lock lock=new ReentrantLock();

    /**
     * 日志对象
     */
    protected Logger logger = LoggerFactory.getLogger(getClass());

    @Override
    public void run() {
        lock.lock();
        int i=0;
        RedisUtil redisUtil = SpringContextHolder.getBean(RedisUtil.class);
        Object price = redisUtil.get("price");
        i = Integer.parseInt(price.toString())-1;
        System.out.println(i);
        redisUtil.set("price",i);
        logger.warn(Thread.currentThread().getName());
        System.out.println("当前线程名： "+ Thread.currentThread().getName()+" ,i = "+i);
        lock.unlock();
    }


    //测试多线程
    @RequestMapping("/getManyThread")
    public  void getManyThread() {
        MyReenrantLock myReenrantLock = new MyReenrantLock();
        Thread thread  = new Thread(myReenrantLock);
        Thread thread1 = new Thread(myReenrantLock);
        Thread thread2 = new Thread(myReenrantLock);
        Thread thread3 = new Thread(myReenrantLock);
        thread.start();
        thread1.start();
        thread2.start();
        thread3.start();
    }

}
